package cn.com.anypay.manager.service.impl;

import cn.com.anypay.manager.service.OssService;
import cn.com.anysdk.oss.api.IOssConfig;
import cn.com.anysdk.oss.api.IOssService;
import cn.com.anysdk.oss.api.UploadOptions;
import cn.com.anysdk.oss.config.AliyunOssConfig;
import cn.com.anysdk.oss.config.LocalFileSystemConfig;
import cn.com.anysdk.oss.config.MinioConfig;
import cn.com.anysdk.oss.config.TencentCloudOssConfig;
import cn.com.anysdk.oss.exception.OssException;
import cn.com.anysdk.oss.impl.OssServiceManager;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
@Service
public class OssServiceImpl implements OssService {

    @Resource
    OssServiceManager manager;



    @Override
    public String switchProvider(Map<String, Object> config) {
        IOssConfig ossConfig = createConfigFromMap(config);
        IOssService ossService =  manager.switchProvider(ossConfig);
        return "OSS Provider switched to: " + ossConfig.getProvider();
    }

    @Override
    public IOssService getCurrentService() {
        return manager.getCurrentService();
    }

    @Override
    public Map<String, Object> uploadFile(MultipartFile file, String path, boolean isPublic) {
        if (file == null || file.isEmpty()) {
            throw new OssException("文件不能为空");
        }
        
        try {
            // 创建临时文件
            Path tempPath = Files.createTempFile("upload-", file.getOriginalFilename());
            file.transferTo(tempPath.toFile());
            
            // 设置上传选项
            UploadOptions options = isPublic ? UploadOptions.publicFile() : UploadOptions.privateFile(3600L);
            
            // 构建对象键
            String objectKey = path != null ? path + "/" + file.getOriginalFilename() : 
                "uploads/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd/")) + file.getOriginalFilename();
            
            // 获取当前OSS服务并上传文件
            IOssService service = getCurrentService();
            if (service == null) {
                throw new OssException("OSS服务未初始化，请先配置存储服务");
            }
            
            String url = service.uploadFile(objectKey, tempPath.toFile(), options);
            
            // 清理临时文件
            Files.delete(tempPath);

            // 构建返回结果
            Map<String,Object> result = new HashMap<>();
            result.put("url", url);
            result.put("path", objectKey);
            result.put("name", file.getOriginalFilename());
            result.put("size", file.getSize());
            result.put("type", file.getContentType());
            result.put("isPublic", isPublic);
            result.put("createTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            return result;

        } catch (IOException e) {
            throw new OssException("文件上传失败: " + e.getMessage(), e);
        } catch (Exception e) {
            throw new OssException("文件上传过程中发生错误: " + e.getMessage(), e);
        }
    }

    @Override
    public Map<String, Object> deleteFile(String path) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取当前OSS服务
            IOssService service = getCurrentService();
            if (service == null) {
                throw new OssException("OSS服务未初始化，请先配置存储服务");
            }

            // 检查文件是否存在
            if (!service.doesObjectExist(path)) {
                result.put("success", false);
                result.put("message", "文件不存在");
                return result;
            }

            // 删除文件
            service.deleteFile(path);
            
            result.put("success", true);
            result.put("message", "文件删除成功");
            result.put("path", path);
            return result;
        } catch (OssException e) {
            throw e;
        } catch (Exception e) {
            throw new OssException("文件删除失败: " + e.getMessage(), e);
        }
    }


    private IOssConfig createConfigFromMap(Map<String, Object> map) {
        String provider = (String) map.get("type");
        if (provider == null) {
            throw new OssException("Missing provider type");
        }
        return switch (provider.toLowerCase()) {
            case "aliyun" -> {
                String endpoint = (String) map.get("endpoint");
                String accessKeyId = (String) map.get("accessKeyId");
                String accessKeySecret = (String) map.get("accessKeySecret");
                String bucket = (String) map.get("bucket");
                if (endpoint == null || endpoint.isEmpty() ||
                    accessKeyId == null || accessKeyId.isEmpty() ||
                    accessKeySecret == null || accessKeySecret.isEmpty() ||
                    bucket == null || bucket.isEmpty()) {
                    throw new OssException("OSS配置缺少必要参数");
                }
                yield AliyunOssConfig.builder()
                        .endpoint(endpoint)
                        .accessKeyId(accessKeyId)
                        .accessKeySecret(accessKeySecret)
                        .bucketName(bucket)
                        .isPrivate(false)
                        .build();
            }
            case "tencent" -> {
                String endpoint = (String) map.get("endpoint");
                String accessKeyId = (String) map.get("accessKeyId");
                String accessKeySecret = (String) map.get("accessKeySecret");
                String bucket = (String) map.get("bucket");
                if (endpoint == null || endpoint.isEmpty() ||
                    accessKeyId == null || accessKeyId.isEmpty() ||
                    accessKeySecret == null || accessKeySecret.isEmpty() ||
                    bucket == null || bucket.isEmpty()) {
                    throw new OssException("OSS配置缺少必要参数");
                }
                yield TencentCloudOssConfig.builder()
                        .endpoint(endpoint)
                        .accessKeyId(accessKeyId)
                        .accessKeySecret(accessKeySecret)
                        .bucketName(bucket)
                        .isPrivate(false)
                        .build();
            }
            case "minio" -> {
                String endpoint = (String) map.get("endpoint");
                String accessKeyId = (String) map.get("accessKeyId");
                String accessKeySecret = (String) map.get("accessKeySecret");
                String bucket = (String) map.get("bucket");
                if (endpoint == null || endpoint.isEmpty() ||
                    accessKeyId == null || accessKeyId.isEmpty() ||
                    accessKeySecret == null || accessKeySecret.isEmpty() ||
                    bucket == null || bucket.isEmpty()) {
                    throw new OssException("OSS配置缺少必要参数");
                }
                yield MinioConfig.builder()
                        .endpoint(endpoint)
                        .accessKeyId(accessKeyId)
                        .accessKeySecret(accessKeySecret)
                        .bucketName(bucket)
                        .isPrivate(false)
                        .build();
            }
            case "local" -> new LocalFileSystemConfig();
            default -> throw new OssException("Unsupported provider: " + provider);
        };
    }
    }
